package com.lisa.auto.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lisa.auto.entity.C3HistoryTrail;
import com.lisa.auto.entity.Vehicle;
import com.lisa.auto.enums.C3UrlEnum;
import com.lisa.auto.mapper.C3HistoryTrailMapper;
import com.lisa.auto.service.C3HistoryTrailService;
import com.lisa.auto.service.IVehicleService;
import com.lisa.auto.util.basic.BaseException;
import com.lisa.auto.util.basic.BaseResponse;
import com.lisa.redis.JedisClusterUtil;
import demo.C3ApiDemo;
import demo.request.HistoryCarInfoRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 车辆历史轨迹信息 服务实现类
 * </p>
 *
 * @author suohao
 * @since 2019-12-20
 */
@Service
public class C3HistoryTrailServiceImpl extends ServiceImpl<C3HistoryTrailMapper, C3HistoryTrail> implements C3HistoryTrailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(C3HistoryTrailServiceImpl.class);

    @Value("${c3.url}")
    private String c3url;
    @Value("${c3.appKey}")
    private String appKey;
    @Value("${c3.secretKey}")
    private String secretKey;
    @Autowired
    private IVehicleService vehicleService;

    @Override
    public List<C3HistoryTrail> getHistoryTrailList(String vin) {
        EntityWrapper<C3HistoryTrail> ew = new EntityWrapper<>();
        ew.eq("vin",vin);
        List<C3HistoryTrail> historyTrailList = baseMapper.getHistoryTrailList(ew);
        return historyTrailList;
    }

    @Override
    public List<C3HistoryTrail> getHistoryTrailListC3(String vin,Long startTime,Long endTime){
        try {
            String url= c3url+ C3UrlEnum.VEHICLEHISTORYTRAILURL.getUrl();
            HistoryCarInfoRequest request = new HistoryCarInfoRequest();
            request.setVin(vin);

            //获取当前时间减1天的时间戳
//            Date date = new Date();//获取当前时间    
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(date);
//            calendar.add(Calendar.DATE, -1);
            //Long startTime = calendar.getTime().getTime();
            request.setEndTime(endTime);
            request.setStartTime(startTime);
            request.setAppKey(appKey);
            String requstJson = JSON.toJSONString(request);
            String result = C3ApiDemo.get(url, requstJson, secretKey);
            if (StringUtils.isNotBlank(result)){
                BaseResponse<C3HistoryTrail> baseResponse = JSONObject.parseObject(result, BaseResponse.class);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (!baseResponse.isReturnSuccess()){
                    throw new BaseException("车辆历史轨迹查询:"+baseResponse.getReturnErrMsg());
                }
                List<C3HistoryTrail> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), C3HistoryTrail.class);
                return list;
            }
        }catch (Exception e){
            LOGGER.error("C3HistoryTrailServiceImpl.getHistoryTrailListC3 ERROR {}", e.getMessage());
            throw new BaseException(e.getMessage());
        }
        return null;
    }

    @Override
    public void historyTrailToRedis() {
        //查询所有的车辆信息
        EntityWrapper<Vehicle> ew = new EntityWrapper<>();
        ew.eq("status",10);
        List<Vehicle> vehicles = vehicleService.selectList(ew);
        for (Vehicle vehicle : vehicles) {
            //获取一天前的历史轨迹,存入redis
            String date = getDate(-1);
            List<C3HistoryTrail> historyTrailListC3 = getHistoryTrailListC3(vehicle.getVin(), getTimestamp(-1), getTimestamp(0));
            JedisClusterUtil.hSet(vehicle.getVin(),vehicle.getVin()+"_"+date,JSONObject.toJSONString(historyTrailListC3));

            //获取两天前的历史轨迹,存入redis
            String date1 = getDate(-2);
            List<C3HistoryTrail> historyTrailListC31 = getHistoryTrailListC3(vehicle.getVin(), getTimestamp(-2), getTimestamp(-1));
            JedisClusterUtil.hSet(vehicle.getVin(),vehicle.getVin()+"_"+date1,JSONObject.toJSONString(historyTrailListC31));

            //获取三天前的历史轨迹,存入redis
            String date2 = getDate(-3);
            List<C3HistoryTrail> historyTrailListC32 = getHistoryTrailListC3(vehicle.getVin(), getTimestamp(-3), getTimestamp(-2));
            JedisClusterUtil.hSet(vehicle.getVin(),vehicle.getVin()+"_"+date2,JSONObject.toJSONString(historyTrailListC32));

            //只保留三天的历史轨迹，判断第四天的是否存在  若存在就删除
            boolean exists = JedisClusterUtil.hExists(vehicle.getVin(),vehicle.getVin()+"_"+getDate(-4));
            if (exists){
                JedisClusterUtil.hDel(vehicle.getVin(),vehicle.getVin()+"_"+getDate(-4));
            }
        }
    }


    /***
     * 获取指定的时间格式字符串
     * @param amount
     * @return
     */
    private String getDate(int amount){
        List list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,amount);
        Date d=cal.getTime();
        String date1 = sdf.format(d);
        return date1;
    }

    /***
     * 获取指定的时间的起始时间戳
     * @param amount
     * @return
     */
    private long getTimestamp(int amount){
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)+amount,0,0,0);
        return calendar.getTime().getTime();
    }
}
